package com.example.hrsystem.ui.user;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.hrsystem.R;
import com.example.hrsystem.data.model.User;
import com.example.hrsystem.data.repository.UserRepository;

public class RegisterActivity extends AppCompatActivity {

    private EditText phoneNumberEditText;
    private EditText verificationCodeEditText;
    private EditText passwordEditText;
    private EditText confirmPasswordEditText;
    private Button getVerificationCodeButton;
    private Button registerButton;
    private Button backButton;

    private CountDownTimer countDownTimer;
    private UserRepository userRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {
            setContentView(R.layout.register_activity);

            // 初始化用户仓库
            try {
                userRepository = new UserRepository(getApplication());
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "初始化失败，请重启应用", Toast.LENGTH_SHORT).show();
            }

            // 初始化UI组件
            try {
                phoneNumberEditText = findViewById(R.id.phone_number_edit_text);
                verificationCodeEditText = findViewById(R.id.verification_code_edit_text);
                passwordEditText = findViewById(R.id.password_edit_text);
                confirmPasswordEditText = findViewById(R.id.confirm_password_edit_text);
                getVerificationCodeButton = findViewById(R.id.get_verification_code_button);
                registerButton = findViewById(R.id.register_button);
                backButton = findViewById(R.id.back_button);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "界面加载失败", Toast.LENGTH_SHORT).show();
            }

            // 设置返回按钮点击事件
            try {
                if (backButton != null) {
                    backButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 设置获取验证码按钮点击事件
            try {
                if (getVerificationCodeButton != null) {
                    getVerificationCodeButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            handleGetVerificationCode();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 设置注册按钮点击事件
            try {
                if (registerButton != null) {
                    registerButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            handleRegister();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "注册页面加载失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理获取验证码逻辑
     */
    private void handleGetVerificationCode() {
        try {
            if (phoneNumberEditText == null) {
                Toast.makeText(this, "界面组件未初始化", Toast.LENGTH_SHORT).show();
                return;
            }

            String phoneNumber = phoneNumberEditText.getText().toString().trim();

            // 验证手机号格式
            if (!isValidPhoneNumber(phoneNumber)) {
                Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
                return;
            }

            // 模拟发送验证码
            Toast.makeText(this, "验证码已发送", Toast.LENGTH_SHORT).show();

            // 倒计时60秒，期间按钮不可点击
            startCountDownTimer();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "获取验证码失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理注册逻辑
     */
    private void handleRegister() {
        try {
            if (phoneNumberEditText == null || verificationCodeEditText == null || 
                passwordEditText == null || confirmPasswordEditText == null) {
                Toast.makeText(this, "界面组件未初始化", Toast.LENGTH_SHORT).show();
                return;
            }

            String phoneNumber = phoneNumberEditText.getText().toString().trim();
            String verificationCode = verificationCodeEditText.getText().toString().trim();
            String password = passwordEditText.getText().toString().trim();
            String confirmPassword = confirmPasswordEditText.getText().toString().trim();

            // 输入校验
            if (!isValidPhoneNumber(phoneNumber)) {
                Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(verificationCode) || verificationCode.length() != 6) {
                Toast.makeText(this, "请输入6位验证码", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!isValidPassword(password)) {
                Toast.makeText(this, "密码长度应为6-20位", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!password.equals(confirmPassword)) {
                Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                return;
            }

            // 使用回调版本检查手机号是否已存在
            try {
                userRepository.isPhoneNumberExists(phoneNumber, new UserRepository.PhoneNumberExistsCallback() {
                    @Override
                    public void onResult(boolean exists) {
                        try {
                            if (exists) {
                                // 手机号已存在
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(RegisterActivity.this, "该手机号已注册，请更换手机号", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } else {
                                // 手机号不存在，创建新用户并保存到数据库
                                saveNewUserToDatabase(phoneNumber, password);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(RegisterActivity.this, "处理注册结果失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "检查手机号失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "注册处理异常", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 保存新用户到数据库
     */
    private void saveNewUserToDatabase(String phoneNumber, String password) {
        try {
            // 创建新用户对象
            User user = new User();
            user.setPhoneNumber(phoneNumber);
            user.setPassword(password);
            // 为新用户设置默认值
            user.setName("新用户");
            
            // 生成员工ID时添加异常处理
            try {
                user.setEmployeeId(generateEmployeeId());
            } catch (Exception e) {
                e.printStackTrace();
                user.setEmployeeId("EMP" + System.currentTimeMillis()); // 备用方案
            }
            
            user.setDepartment("待定");
            user.setPosition("待定");
            user.setEmail(phoneNumber + "@example.com");
            
            // 获取当前日期时添加异常处理
            try {
                user.setEntryDate(getCurrentDate());
            } catch (Exception e) {
                e.printStackTrace();
                user.setEntryDate("" + System.currentTimeMillis()); // 备用方案
            }
            
            user.setUserType("普通员工");
            user.setActive(true);

            // 保存用户到数据库
            try {
                userRepository.insert(user);
            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(RegisterActivity.this, "保存用户失败", Toast.LENGTH_SHORT).show();
                    }
                });
                return;
            }

            // 注册成功后跳转到登录页面
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(RegisterActivity.this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
                }
            });
            
            // 延迟一小段时间让用户看到Toast提示
            try {
                new android.os.Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                            startActivity(intent);
                            // 暂时移除动画，避免资源问题
                            // overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(RegisterActivity.this, "跳转到登录页失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }, 1000);
            } catch (Exception e) {
                e.printStackTrace();
                // 即使延迟跳转失败，也要确保能跳转到登录页
                try {
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(RegisterActivity.this, "用户创建失败", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 生成员工工号
     */
    private String generateEmployeeId() {
        try {
            // 简单生成工号：EMP+当前时间戳
            long timestamp = System.currentTimeMillis();
            return "EMP" + timestamp;
        } catch (Exception e) {
            e.printStackTrace();
            return "EMP" + System.nanoTime(); // 备用方案
        }
    }

    /**
     * 获取当前日期，格式为yyyy-MM-dd
     */
    private String getCurrentDate() {
        try {
            java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault());
            return dateFormat.format(new java.util.Date());
        } catch (Exception e) {
            e.printStackTrace();
            return "" + System.currentTimeMillis(); // 备用方案
        }
    }

    /**
     * 验证手机号格式是否正确
     */
    private boolean isValidPhoneNumber(String phoneNumber) {
        // 简单的手机号格式校验，中国大陆手机号通常为11位数字
        return !TextUtils.isEmpty(phoneNumber) && phoneNumber.length() == 11 && phoneNumber.matches("[0-9]+");
    }

    /**
     * 验证密码格式是否正确
     */
    private boolean isValidPassword(String password) {
        // 密码长度校验
        return !TextUtils.isEmpty(password) && password.length() >= 6 && password.length() <= 20;
    }

    /**
     * 开始倒计时
     */
    private void startCountDownTimer() {
        try {
            if (getVerificationCodeButton == null) {
                return;
            }
            
            getVerificationCodeButton.setEnabled(false);

            // 取消可能存在的旧计时器
            if (countDownTimer != null) {
                countDownTimer.cancel();
            }

            countDownTimer = new CountDownTimer(60000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    try {
                        if (getVerificationCodeButton != null) {
                            getVerificationCodeButton.setText("重新获取(" + millisUntilFinished / 1000 + ")");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFinish() {
                    try {
                        if (getVerificationCodeButton != null) {
                            getVerificationCodeButton.setEnabled(true);
                            getVerificationCodeButton.setText("获取验证码");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            countDownTimer.start();
        } catch (Exception e) {
            e.printStackTrace();
            // 出错时确保按钮可用
            try {
                if (getVerificationCodeButton != null) {
                    getVerificationCodeButton.setEnabled(true);
                    getVerificationCodeButton.setText("获取验证码");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        try {
            super.onDestroy();
            // 确保在Activity销毁时取消倒计时
            if (countDownTimer != null) {
                countDownTimer.cancel();
                countDownTimer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}